package net.wanho.handler;

import cn.hutool.json.JSONUtil;
import net.wanho.vo.AjaxResult;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 网关统一异常处理
 */
@Order(-1)
@Configuration
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse res = exchange.getResponse();
        String jsonStr = JSONUtil.toJsonStr(AjaxResult.error(ex.getMessage()));
        DataBuffer buffer = res.bufferFactory().wrap(jsonStr.getBytes(StandardCharsets.UTF_8));
        res.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return res.writeWith(Mono.just(buffer));
    }
}